package com.wang.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

/**
 * http的工具类
 * 
 * @author MyJJh
 */
@Component
public class HttpUtil
{

	/**
	 * 模块浏览器发送get请求
	 * @param url	请求网址
	 * @param headerMap	请求头
	 * @param paramsMap	请求体; a=1&b=2&c=3&d=4
	 * @return	是服务器返回的内容
	 */
	public String methodGet(String urlStr, Map<String, String> headerMap, 
			Map<String, String> paramsMap,Map<String,List<String>> responseHeader)
	{
		ConstatFinalUtil.LOGGER.info("==methodGet==");
		
		StringBuilder sb = new StringBuilder();
		
		BufferedWriter bw = null ;
		BufferedReader br = null ; 
		try
		{
			/* get请求的请求体得在url上做处理 */
			sb.delete(0, sb.length());
			/* 存储原来的字符串 */
			sb.append(urlStr);
			if(sb.indexOf("?") == -1 )
			{
				sb.append("?");
			}
			for(Entry me : paramsMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				sb.append("&" + key + "=" + val) ; 
			}
			urlStr = sb.toString() ; 
			/* 得清空sb,因为url拼装和response共用了一个sb */
			sb.delete(0, sb.length());
			ConstatFinalUtil.LOGGER.info("urlStr:{}",urlStr);
			
			/* 创建一个网址====File */
			URL url = new URL(urlStr);
			/* 准备一根管子 */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			ConstatFinalUtil.LOGGER.info("===connection:{}=",connection);
			
			//默认是get请求
			/* 设置超时时间 */
			/* 链接超时;毫秒(网络) */
			connection.setConnectTimeout(10000);
			/* 读取超时;毫秒(数量量大) */
			connection.setReadTimeout(10000);
			
			/* 存储请求头 */
			for(Entry me : headerMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				connection.setRequestProperty(key, val);
			}
			
			/* get请求输入流不能写 */
//			OutputStream os = connection.getOutputStream();
//			bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			
			// 为响应码赋值
			responseHeader.putAll(connection.getHeaderFields()) ; 
			
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			
			String line = "" ; 
			while( ( line = br.readLine() ) != null)
			{
				sb.append(line);
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
		} finally
		{
			try
			{
				if(br != null )
				{
					br.close();
					br = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
			
			try
			{
				if(bw != null)
				{
					bw.close();
					bw = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
		}
		return sb.toString() ; 
	}
	
	/**
	 * 模块浏览器发送post请求
	 * @param url	请求网址
	 * @param headerMap	请求头
	 * @param paramsMap	请求体; a=1&b=2&c=3&d=4
	 * @return	是服务器返回的内容
	 */
	public String methodPost(String urlStr, Map<String, String> headerMap, 
			Map<String, String> paramsMap,Map<String,List<String>> responseHeader)
	{
		ConstatFinalUtil.LOGGER.info("==methodPost==");
		
		StringBuilder sb = new StringBuilder();
		
		BufferedWriter bw = null ;
		BufferedReader br = null ; 
		try
		{
			/* 创建一个网址====File */
			URL url = new URL(urlStr);
			/* 准备一根管子 */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			ConstatFinalUtil.LOGGER.info("===connection:{}=",connection);
			
			//默认是post请求
			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			/* 设置超时时间 */
			/* 链接超时;毫秒(网络) */
			connection.setConnectTimeout(10000);
			/* 读取超时;毫秒(数量量大) */
			connection.setReadTimeout(10000);
			
			/* 存储请求头 */
			for(Entry me : headerMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				connection.setRequestProperty(key, val);
			}
			
			/* get请求输入流不能写 */
			OutputStream os = connection.getOutputStream();
			bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			
			sb.delete(0, sb.length());
			for(Entry me : paramsMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				sb.append("&" + key + "=" + val) ; 
			}
			bw.write(sb.toString());
			bw.flush();
			bw.close();
			
			ConstatFinalUtil.LOGGER.info("==状态码:{}=信息:{}",connection.getResponseCode() ,connection.getResponseMessage());
			
			sb.delete(0, sb.length());
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			
//			/* 响应头 */
//			Map<String, List<String>> headerFieldsMap = connection.getHeaderFields();
//			for(Entry me : headerFieldsMap.entrySet())
//			{
//				String key = me.getKey() + "" ; 
//				List<String> val = (List<String>) me.getValue() ; 
//				ConstatFinalUtil.LOGGER.info("响应头:key:{},val:{}",key, val);
//			}
			// 为响应码赋值
			responseHeader.putAll(connection.getHeaderFields()) ; 
			
			String line = "" ; 
			while( ( line = br.readLine() ) != null)
			{
				sb.append(line);
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
		} finally
		{
			try
			{
				if(br != null )
				{
					br.close();
					br = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
			
			try
			{
				if(bw != null)
				{
					bw.close();
					bw = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
		}
		return sb.toString() ; 
	}
}
